﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Enterprise.Model.User;
using Enterprise.Data.User;
using Enterprise.Infrastructure;
using Enterprise.Data.Email;
using System.Data;

namespace Enterprise.Service.User
{
    /// <summary>
    /// 用户业务服务
    /// </summary>
    public class UserService
    {
        /// <summary>
        /// 用户缓存标记
        /// </summary>
        private static string cacheKey = "Enterprise-User";

        /// <summary>
        /// 人员列表 返回所有人员记录
        /// </summary>
        /// <returns></returns>
        public List<UserEntity> UserList()
        {
            if (CacheHelper.Contains(cacheKey))
            {
                return (List<UserEntity>)CacheHelper.GetCache(cacheKey);
            }
            else
            {
                UserData data = new UserData();
                List<UserEntity> list=data.UserList();
                CacheHelper.Add(cacheKey, list);
                return list;
            }
        }

        /// <summary>
        /// 返回人员记录信息
        /// </summary>
        /// <param name="Id">人员编码</param>
        /// <returns></returns>
        public UserEntity UserDisp(int Id)
        {
            return UserList().Where(p => p.USERID == Id).FirstOrDefault();
        }

        /// <summary>
        /// 人员排序上移操作方法
        /// </summary>
        /// <param name="Id">人员编号</param>
        public void UserMoveUpService(int Id)
        {
            var entity = UserDisp(Id);
            if (entity != null)
            {
                var upentity = UserList().Where(p => p.DEPTID == entity.DEPTID && p.UORDERBY<entity.UORDERBY).OrderByDescending(p=>p.UORDERBY).FirstOrDefault();
                if (upentity != null)
                {
                    string upcmd = "Update SYS_USER set UORDERBY=" + entity.UORDERBY + "where USERID=" + upentity.USERID;
                    UserExecuteBySql(upcmd, 0);
                    string cmd = "Update SYS_USER set UORDERBY=" + upentity.UORDERBY + " where USERID=" + entity.USERID;
                    UserExecuteBySql(cmd, 0);
                    ClearCache();
                }
            }
        }

        /// <summary>
        /// 人员排序下移操作方法
        /// </summary>
        /// <param name="Id">人员编号</param>
        public void UserMoveDownService(int Id)
        {
            var entity = UserDisp(Id);
            if (entity != null)
            {
                var downentity = UserList().Where(p => p.DEPTID == entity.DEPTID && p.UORDERBY>entity.UORDERBY + 1).OrderBy(p=>p.UORDERBY).FirstOrDefault();
                if (downentity != null)
                {
                    string upcmd = "Update SYS_USER set UORDERBY=" + (entity.UORDERBY) + "where USERID=" + downentity.USERID;
                    UserExecuteBySql(upcmd, 0);
                    string cmd = "Update SYS_USER set UORDERBY=" +downentity.UORDERBY+ " where USERID=" + entity.USERID;
                    UserExecuteBySql(cmd, 0);
                    ClearCache();
                }
            }
        }

        private void ClearCache()
        {
            CacheHelper.RemoveCache(cacheKey);
        }

        /// <summary>
        ///  返回部门下人员最大排序序号
        /// </summary>
        /// <param name="deptId"></param>
        /// <returns></returns>
        public int GetMaxUserOrderBy(int deptId)
        {
            var q = UserList().Where(p => p.DEPTID == deptId).OrderByDescending(p => p.UORDERBY).FirstOrDefault();
            if (q != null)
            {
                return q.UORDERBY;
            }
            return 0;
        }

        /// <summary>
        ///  返回人员姓名
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static string GetUserName(int userId)
        {
            string reStr = "";
            UserService uService = new UserService();
            var q = uService.UserDisp(userId);
            if (q != null)
            {
                return q.UNAME;
            }
            return reStr;
        }

        /// <summary>
        ///  返回人员所在部门
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static int GetUserDeptId(int userId)
        {
            UserService uService = new UserService();
            var q = uService.UserDisp(userId);
            if (q != null)
            {
                return q.DEPTID;
            }
            return 0;
        }

        /// <summary>
        ///  返回人员姓名
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        public static string GetUserName(int userId,out int deptId)
        {
            string reStr = "";
            UserService uService = new UserService();
            var q = uService.UserDisp(userId);
            if (q != null)
            {
                deptId = q.DEPTID;
                return q.UNAME;
            }
            deptId = 0;
            return reStr;
        }

        /// <summary>
        /// 按数组返回人员信息
        /// </summary>
        /// <param name="uArray"></param>
        /// <returns></returns>
        public static string GetUserNameArray(string uArray)
        {
            string str = "";
            if (!string.IsNullOrEmpty(uArray))
            {
                string[] paths = uArray.Split(',');
                if (paths.Length > 1)
                {
                    for (int i = 0; i < paths.Length; i++)
                    {
                        string uName = GetUserName(int.Parse(paths[i].ToString()));
                        if (!string.IsNullOrEmpty(uName))
                        {
                            str += uName+"; ";
                        }
                    }
                }
            }
            return str.TrimEnd(';');
        }

        /// <summary>
        /// 人员操作 添加、修改、删除
        /// </summary>
        /// <param name="entity">用户实体</param>
        public void UserExecute(UserEntity entity)
        {
            string cmd = string.Empty;
            switch (entity.DB_Option_Action)
            {
                case "Insert":
                    cmd = "Insert into sys_user(DEPTID,ULOGINNAME,ULOGINPASS,UNAME,USEX,UBIRTHDAY,UHWPHONE,UGNPHONE,SIPCEMAIL,OTHEREMAIL,UIP,UADMIN,USTATUS,UORDERBY) values(" + entity.DEPTID + ",'" + entity.ULOGINNAME + "','" + entity.ULOGINPASS + "','" + entity.UNAME + "','" + entity.USEX + "'," + Utility.FormatOracleDate(entity.UBIRTHDAY) + ",'" + entity.UHWPHONE + "','" + entity.UGNPHONE + "','" + entity.SIPCEMAIL + "','" + entity.OTHEREMAIL + "','" + entity.UIP + "','" + entity.UADMIN + "','" + entity.USTATUS + "'," + entity.UORDERBY + ")";
                    break;
                case "Update":
                    cmd = "Update sys_user set DEPTID=" + entity.DEPTID + ", UNAME='" + entity.UNAME + "' , USEX='" + entity.USEX + "' , UBIRTHDAY=" + Utility.FormatOracleDate(entity.UBIRTHDAY) + ",UHWPHONE='" + entity.UHWPHONE + "',UGNPHONE='" + entity.UGNPHONE + "',SIPCEMAIL='" + entity.SIPCEMAIL + "',OTHEREMAIL='" + entity.OTHEREMAIL + "',UIP='" + entity.UIP + "' , UADMIN='" + entity.UADMIN + "' , USTATUS='" + entity.USTATUS + "' , UORDERBY=" + entity.UORDERBY + " where USERID=" + entity.USERID;
                    break;
                case "Delete":
                    cmd = "Delete from sys_user where USERID=" + entity.USERID;
                    break;
            }
            if (!string.IsNullOrEmpty(cmd))
            {
                UserExecuteBySql(cmd,1);
            }
        }

        /// <summary>
        /// 人员操作方法
        /// </summary>
        /// <param name="cmd"></param>
        /// <param name="typeId">1:刷新缓存 0:不刷新缓存 </param>
        public void UserExecuteBySql(string cmd,int typeId)
        {
            UserData data = new UserData();
            data.UserExecute(cmd);
            if (typeId == 1)
            {
                ClearCache();
            }
        }

        /// <summary>
        /// 返回人员集合@将部门和人员机构生成到一张数据表,便于生成基于部门的用户树结构
        /// </summary>
        /// <returns></returns>
        public DataSet GetRelationForCombox()
        {
            UserData data = new UserData();
            string sql = @"select * from (
select 'd-'||to_char(a.deptid) as cid, a.dname as text ,'d-'||a.dparentid as parentid , a.dorderby as orderby from sys_department a
                union
            (select to_char(b.userid) as cid,b.uname as text ,'d-'||to_char(b.deptid) as parentid, b.uorderby as orderby  from sys_user b)
            ) order by orderby asc";
            return data.ExcuteDataSet(sql);
        }

        /// <summary>
        /// 未读邮件数量
        /// </summary>
        /// <param name="userId">用户Id</param>
        public int NotReadMailCount(int userId)
        {                    
            EMailData ed = new EMailData();
            return ed.NotReadCount(userId);
        }

    }
}
